package com.dims_hsrc.web.controller.audit;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.dims_hsrc.audit.domain.ContractRecord;
import com.dims_hsrc.audit.service.IContractRecordService;
import com.dims_hsrc.audit.service.IContractBlockchainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.dims_hsrc.common.annotation.Log;
import com.dims_hsrc.common.core.controller.BaseController;
import com.dims_hsrc.common.core.domain.AjaxResult;
import com.dims_hsrc.common.core.page.TableDataInfo;
import com.dims_hsrc.common.enums.BusinessType;
import com.dims_hsrc.common.utils.poi.ExcelUtil;
import com.dims_hsrc.common.utils.SecurityUtils;
import com.dims_hsrc.common.utils.StringUtils;



/**
 * 合同管理Controller
 * 
 * @author 赵浩然
 */
@RestController
@RequestMapping("/audit/contract")
public class ContractController extends BaseController 
{
    @Autowired
    private IContractRecordService contractRecordService;
    
    @Autowired
    private IContractBlockchainService contractBlockchainService;


    /**
     * 查询合同记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ContractRecord contractRecord)
    {
        startPage();
        List<ContractRecord> list = contractRecordService.selectContractRecordList(contractRecord);
        return getDataTable(list);
    }

    /**
     * 导出合同记录列表
     */
    @Log(title = "合同记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ContractRecord contractRecord)
    {
        List<ContractRecord> list = contractRecordService.selectContractRecordList(contractRecord);
        ExcelUtil<ContractRecord> util = new ExcelUtil<ContractRecord>(ContractRecord.class);
        return util.exportExcel(list, "合同记录数据");
    }

    /**
     * 获取合同记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(contractRecordService.selectContractRecordById(id));
    }
    
    /**
     * 根据结构ID获取合同列表
     */
    @GetMapping(value = "/struct/{structId}")
    public AjaxResult listByStructId(@PathVariable("structId") String structId)
    {
        List<ContractRecord> list = contractRecordService.selectContractRecordsByStructId(structId);
        return success(list);
    }
    
    /**
     * 生成合同
     */
    @Log(title = "生成合同", businessType = BusinessType.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody ContractRecord contractRecord)
    {
        // 设置创建人
        contractRecord.setCreateBy(SecurityUtils.getUsername());
        
        try {
            ContractRecord result = contractRecordService.generateContract(contractRecord);
            return success(result);
        } catch (Exception e) {
            return error("生成合同失败: " + e.getMessage());
        }
    }
    
    /**
     * 下载合同文件
     */
    @GetMapping("/download/{contractNo}")
    public void download(@PathVariable("contractNo") String contractNo, HttpServletResponse response) throws IOException 
    {
        try {
            // 获取文件路径
            String filePath = contractRecordService.getContractFilePath(contractNo);
            
            // 获取文件名
            File file = new File(filePath);
            if (!file.exists()) {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("文件不存在");
                return;
            }
            
            String fileName = file.getName();
            
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            response.setContentLength((int) file.length());
            
            // 使用输入输出流复制文件内容
            try (InputStream inputStream = new FileInputStream(file);
                 OutputStream outputStream = response.getOutputStream()) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("下载文件失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除合同记录
     */
    @Log(title = "合同记录", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable("ids") String ids)
    {
        return toAjax(contractRecordService.deleteContractRecordByIds(ids));
    }

    /**
     * 更新合同状态
     */
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody ContractRecord contractRecord)
    {
        // 设置更新人
        contractRecord.setCreateBy(SecurityUtils.getUsername());
        return toAjax(contractRecordService.updateContractStatus(contractRecord));
    }

    /**
     * 获取合同模板列表
     */
    @GetMapping("/templates")
    public AjaxResult listTemplates()
    {
        // 定义模板目录路径
        String templatesPath = "D:/GraduateWork/dev/DIMS-HSRC/contract/templates";
        
        List<Map<String, String>> templates = new ArrayList<>();
        File templatesDir = new File(templatesPath);
        
        if (templatesDir.exists() && templatesDir.isDirectory()) {
            File[] files = templatesDir.listFiles((dir, name) -> 
                name.toLowerCase().endsWith(".docx") || name.toLowerCase().endsWith(".doc"));
            
            if (files != null) {
                for (File file : files) {
                    Map<String, String> template = new HashMap<>();
                    template.put("name", file.getName());
                    template.put("path", "contract/templates/" + file.getName());
                    templates.add(template);
                }
            }
        }
        
        // 如果没有找到模板，添加一个默认模板
        if (templates.isEmpty()) {
            Map<String, String> defaultTemplate = new HashMap<>();
            defaultTemplate.put("name", "默认模板");
            defaultTemplate.put("path", "contract/templates/contract_template.docx");
            templates.add(defaultTemplate);
        }
        
        return success(templates);
    }

    /**
     * 上传合同到区块链
     */
    @Log(title = "上传合同到区块链", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadToChain/{contractNo}")
    public AjaxResult uploadToChain(@PathVariable("contractNo") String contractNo)
    {
        try {
            Map<String, Object> result = contractBlockchainService.uploadContractToChain(contractNo);
            return success(result);
        } catch (Exception e) {
            return error("上传到区块链失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取合同在区块链上的状态
     */
    @GetMapping("/chainStatus/{contractNo}")
    public AjaxResult getChainStatus(@PathVariable("contractNo") String contractNo)
    {
        try {
            Map<String, Object> result = contractBlockchainService.getContractChainStatus(contractNo);
            return success(result);
        } catch (Exception e) {
            return error("获取区块链状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证合同数据与区块链上的数据一致性
     */
    @GetMapping("/verifyChain/{contractNo}")
    public AjaxResult verifyContractOnChain(@PathVariable("contractNo") String contractNo)
    {
        try {
            Map<String, Object> result = contractBlockchainService.verifyContractOnChain(contractNo);
            return success(result);
        } catch (Exception e) {
            return error("验证合同一致性失败: " + e.getMessage());
        }
    }
    
    /**
     * 上传文件进行验证
     */
    @PostMapping("/verifyUpload")
    public AjaxResult verifyUploadedFile(@RequestParam("contractNo") String contractNo, 
                                         @RequestParam("file") MultipartFile file)
    {
        try {
            Map<String, Object> result = contractBlockchainService.verifyUploadedFile(contractNo, file);
            return success(result);
        } catch (Exception e) {
            return error("验证文件失败: " + e.getMessage());
        }
    }

}